import React from 'react';
import { View, Text, Picker } from '@tarojs/components';
import { RegionNode } from '../types/cityBase';

import './ProvinceCitySelector.scss';

interface ProvinceCitySelectorProps {
  onSelect: (path: string[], node?: RegionNode, parentNode?: RegionNode | null) => void;
  chinaRegions: RegionNode[];
  selectedRegionPath?: string[];
  level: 'region' | 'city' | 'province';
  children: React.ReactNode;
  class_name?: string;
}

/**
 * 使用Taro原生Picker组件实现的地区选择器
 */
const ProvinceCitySelector: React.FC<ProvinceCitySelectorProps> = ({
  onSelect,
  children,
  chinaRegions,
  selectedRegionPath,
  level = 'region',
  class_name = 'province-city-selector-wrapper'
}) => {
  const findNodeByPath = (
    nodes: RegionNode[], 
    path: string[], 
    level: number = 0
  ): { node: RegionNode | undefined; parentNode: RegionNode | null } => {
    if (level >= path.length || !nodes || nodes.length === 0) {
      return { node: undefined, parentNode: null };
    }

    const targetNode = nodes.find(node => node.id.toString() === path[level]);
    if (!targetNode) {
      return { node: undefined, parentNode: null };
    }

    // 如果是最后一级，返回当前节点
    if (level === path.length - 1) {
      return { node: targetNode, parentNode: null };
    }

    // 继续向下查找
    const result = findNodeByPath(targetNode.children || [], path, level + 1);
    if (result.node) {
      // 如果找到了目标节点，但还没有父节点，设置父节点为当前节点
      if (!result.parentNode) {
        result.parentNode = targetNode;
      }
    }
    return result;
  };

  // 将ID路径转换为名称路径，用于Picker组件的value属性
  const getRegionNamePath = () => {
    if (!selectedRegionPath || selectedRegionPath.length === 0) {
      return undefined;
    }
    
    const { node, parentNode } = findNodeByPath(chinaRegions, selectedRegionPath);
    const namePath: string[] = [];
    
    // 查找完整的层级路径
    if (node) {
      // 构建完整的路径：[省份, 城市, 区]
      // 1. 首先确定当前节点的级别
      const isDistrict = selectedRegionPath.length === 3;
      const isCity = selectedRegionPath.length === 2;
      const isProvince = selectedRegionPath.length === 1;
      
      // 2. 根据不同级别构建完整的名称路径
      if (isDistrict) {
        // 完整的三级路径
        // 找到省、市、区
        const provinceId = selectedRegionPath[0];
        const cityId = selectedRegionPath[1];
        const districtId = selectedRegionPath[2];
        
        const province = chinaRegions.find(p => p.id.toString() === provinceId);
        const city = province?.children?.find(c => c.id.toString() === cityId);
        const district = city?.children?.find(d => d.id.toString() === districtId);
        
        if (province && city && district) {
          namePath.push(province.name);
          namePath.push(city.name);
          namePath.push(district.name);
        }
      } else if (isCity) {
        // 二级路径：省+市
        const provinceId = selectedRegionPath[0];
        const cityId = selectedRegionPath[1];
        
        const province = chinaRegions.find(p => p.id.toString() === provinceId);
        const city = province?.children?.find(c => c.id.toString() === cityId);
        
        if (province && city) {
          namePath.push(province.name);
          namePath.push(city.name);
          // 如果是region级别，添加空字符串作为区的占位符
          if (level === 'region') {
            namePath.push('');
          }
        }
      } else if (isProvince) {
        // 一级路径：省
        const province = chinaRegions.find(p => p.id.toString() === selectedRegionPath[0]);
        if (province) {
          namePath.push(province.name);
          // 根据level补全路径
          if (level === 'city' || level === 'region') {
            namePath.push('');
            if (level === 'region') {
              namePath.push('');
            }
          }
        }
      }
      
      // 兜底方案：如果以上逻辑没有构建出路径，尝试从node和parentNode中构建
      if (namePath.length === 0) {
        let currentNode = node;
        let parent = parentNode;
        const reversePath: string[] = [currentNode.name];
        
        // 向上查找父节点，直到找到根节点（省份）
        while (parent) {
          reversePath.unshift(parent.name);
          const { parentNode: grandparent } = findNodeByPath(chinaRegions, [parent.id.toString()]);
          parent = grandparent;
        }
        
        // 根据level补全路径
        if (level === 'region' && reversePath.length < 3) {
          const neededEmptyItems = 3 - reversePath.length;
          for (let i = 0; i < neededEmptyItems; i++) {
            reversePath.push('');
          }
        } else if (level === 'city' && reversePath.length < 2) {
          reversePath.push('');
        }
        
        namePath.push(...reversePath);
      }
    }
    
    return namePath;
  };

  const handlePickerChange = (e: any) => {
    // 获取选择的地区信息数组 [province, city, district]
    const regionInfo = e.detail.value;
    if (!regionInfo || regionInfo.length === 0) return;

    // 从chinaRegions中查找匹配的节点信息
    const provinceNode = chinaRegions.find(p => p.name === regionInfo[0]);
    let cityNode: RegionNode | undefined;
    let districtNode: RegionNode | undefined;
    
    if (provinceNode && regionInfo[1]) {
      cityNode = provinceNode.children?.find(c => c.name === regionInfo[1]);
    }
    
    if (cityNode && regionInfo[2] && regionInfo[2] !== '') {
      districtNode = cityNode.children?.find(d => d.name === regionInfo[2]);
    }

    // 构建路径
    const path: string[] = [];
    if (provinceNode) path.push(provinceNode.id.toString());
    if (cityNode) path.push(cityNode.id.toString());
    if (districtNode) path.push(districtNode.id.toString());

    // 调用父组件的onSelect回调
    const selectedNode = districtNode || cityNode || provinceNode;
    const parentNode = districtNode ? cityNode : (cityNode ? provinceNode : null);
    onSelect(path, selectedNode, parentNode);
  };

  const regionNamePath = getRegionNamePath();

  return (
    <View className={class_name}>
      <Picker
        mode="region"
        level={level}
        value={regionNamePath || []}
        regionData={chinaRegions}
        onChange={handlePickerChange}
        defaultValue={regionNamePath || []}
      >
        {children}
      </Picker>
    </View>
  );
};

export default ProvinceCitySelector;